#include "Mpq.h"
#include "stdio.h"

MPQ *Mpq;
MPQ MpqWar3;
MPQ MpqWar3x;
MPQ MpqWar3xLocal;
MPQ MpqWar3Patch;
MPQ MpqCustom;

MPQ::MPQ()
{
	MpqHandle = NULL;
}

MPQ::~MPQ()
{
	Close();
}

bool MPQ::Open(char *FileName)
{
	Close();
	if(!SFileOpenArchive(FileName, 0, 0, &MpqHandle))
	{
		Close();
		//Error.SetMessage("Unable to open \"" + FileName + "\"!");
		return FALSE;
	}

	return TRUE;
}


//+-----------------------------------------------------------------------------
//| Closes the mpq file
//+-----------------------------------------------------------------------------
void MPQ::Close()
{
	if(MpqHandle != NULL)
	{
		SFileCloseArchive(MpqHandle);
		MpqHandle = NULL;
	}
	if(BUFFER != NULL) {
		free(BUFFER);
		BUFFER = NULL;
	}
}

//+-----------------------------------------------------------------------------
//| Loads a file from the mpq to a buffer
//+-----------------------------------------------------------------------------
bool MPQ::LoadFile(char *FileName)
{
	DWORD Size;
	HANDLE FileHandle;
	DWORD BytesRead = 0;

	if(MpqHandle == NULL)
	{
		//Error.SetMessage("Unable to load \"" + FileName + "\", no MPQ file is open!");
		return FALSE;
	}
	if(!SFileOpenFileEx(MpqHandle, FileName, 0, &FileHandle)) return 0;

	Size = SFileGetFileSize(FileHandle, NULL);
	if(BUFFER != NULL) free(BUFFER);
	BUFFER = (char *)malloc(Size);
	if(BUFFER == NULL)
	{
		SFileCloseFile(FileHandle);
		//Error.SetMessage("Unable to resize buffer!");
		return FALSE;
	}

	if(!SFileReadFile(FileHandle, BUFFER, Size, &BytesRead, NULL))
	{
		SFileCloseFile(FileHandle);
		//Error.SetMessage("Unable to read data from \"" + FileName + "\"!");
		free(BUFFER);
		BUFFER = NULL;
		return FALSE;
	}

	SFileCloseFile(FileHandle);

	if(BytesRead != Size)
	{
		//Error.SetMessage("Not all bytes were read from \"" + FileName + "\"!");
		free(BUFFER);
		BUFFER = NULL;
		return FALSE;
	}
	READED = BytesRead;

	return TRUE;
}